import React, { useEffect, useState } from 'react'
import GithubSimpleTable from '../../../components/tables/GithubSimpleTable'
import { Badge, Tag, Avatar, Box, HorizontalStack, Link, List, Text, VerticalStack } from '@shopify/polaris'
import GetPrettifyEndpoint from '../../observe/GetPrettifyEndpoint'
import HttpRequestResponseViewer from './HttpRequestResponseViewer'
import func from '@/util/func'
import transform from './transform';

const Issue = ({ vulnerableApi, references, cwes, compliance, viewMode = 'syntax' }) => {
    const [vulnerableApisState, setVulnerableApisState] = useState([])
    const [vulnerableResultSampleData, setVulnerableResultSampleData] = useState({})

    const testResults = vulnerableApi.testResults

    const resourceName = {
        singular: 'API',
        plural: 'APIs',
    }

    const getTestResultLink = () => {
        const firstVulnerableApi = vulnerableApi
        const testRunResultSummaryHexId = firstVulnerableApi.testRunHexId
        const testRunId = firstVulnerableApi.hexId  

        return `/dashboard/testing/${testRunResultSummaryHexId}?result=${testRunId}`
    }
    const testResultLink = getTestResultLink()

    const apisHeader = (
        <HorizontalStack align="space-between">
           <Text variant="headingXs" fontWeight='bold'>API affected</Text>
           <Link url={testResultLink} removeUnderline target="_blank">
               <Text variant='bodyMd'>See in Akto</Text>
           </Link>   
       </HorizontalStack>
    )
    const headers = [
        {
            text: apisHeader,
            title: apisHeader,
            value: 'apiDetails',
            textValue: 'apiDetailsText'
        }
    ]                

    useEffect(() => {
        const { url, method } = vulnerableApi.apiInfoKey
    
        const apiDetails = (
            <GetPrettifyEndpoint method={method} url={url} isNew={false} />
        )
        
        let vulnerableApis = [{
            key: `${method} ${url}`,
            apiDetailsText: `${method} ${url}`,
            apiDetails: apiDetails,
        }]
    
        setVulnerableApisState(vulnerableApis)
        
        const extractedSampleData = transform.getExtractedVulnerableResultSampleData(testResults)
        setVulnerableResultSampleData(extractedSampleData)
    }, [])

    const [parsedSampleDataMessage, setParsedSampleDataMessage] = useState(null)

    useEffect(() => {
        const tmpParsedSampleDataMessage = transform.getParsedSampleDataMessage(vulnerableResultSampleData)
        setParsedSampleDataMessage(tmpParsedSampleDataMessage)
    }, [vulnerableResultSampleData])

    return (
        <>
            <Box id='affected-api-table-container'>
                <GithubSimpleTable
                    key="table"
                    data={vulnerableApisState}
                    resourceName={resourceName}
                    headers={headers}
                    useNewRow={true}
                    condensedHeight={true}
                    hideQueryField={true}
                    headings={headers}
                    hidePagination={true}
                    showFooter={false}
                />
            </Box>

            {
                parsedSampleDataMessage != null &&
                <VerticalStack gap={1}>
                    <Text variant="headingSm">Evidence</Text>
                    <VerticalStack gap={2}>
                        <HttpRequestResponseViewer data={parsedSampleDataMessage} viewMode={viewMode} />
                    </VerticalStack>
                </VerticalStack>
            }

            <VerticalStack gap={1}>
                <Text variant="headingSm">References</Text>
                <List type="number">
                    {
                        references?.map((reference) => {
                            return (
                                <List.Item>
                                    <Link target="_blank" url={reference}><Text color="subdued">{reference}</Text></Link>
                                </List.Item>
                            )
                        })
                    }
                </List>
            </VerticalStack>

            <VerticalStack gap={1}>
                <Text variant="headingSm">Compliance</Text>
                <HorizontalStack gap="2">
                    {
                    Object.keys(compliance?.mapComplianceToListClauses).map((compliance, index) => {
                        return (
                        <Tag key={index} background="white">
                            <HorizontalStack wrap="false" gap={1}>
                            <Avatar source={func.getComplianceIcon(compliance)} shape="square"  size="extraSmall"/>
                            <Text>{compliance}</Text>
                            </HorizontalStack>  
                        </Tag>
                        )
                    })
                    }
                </HorizontalStack>
            </VerticalStack>
            <VerticalStack gap={1}>
                <Text variant="headingSm">CWE</Text>
                <HorizontalStack gap={2}>
                    {
                        cwes?.map((cweItem) => {
                            return (
                                <Box>
                                    <Badge size="small">{cweItem}</Badge>
                                </Box>
                            )
                        })
                    }
                </HorizontalStack>
            </VerticalStack>
        </>
    )
}

export default Issue